package com.bwie.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.bwie.dao.UserDao;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Override
    public User getUser(String userName) {
        return userDao.getUser(userName);
    }

    @Override
    public int login(User user) {
        User userEntity = userDao.getUser(user.getUserName());
        if (userEntity!=null){
            if (user.getPassword().equals(userEntity.getPassword())){
                Cookie cookie = new Cookie("user", userEntity.getPassword());
//                Cookie cookie = new Cookie("key", "value");
                cookie.setMaxAge(60);
                cookie.setPath("/order/goOrder");
                response.addCookie(cookie);

                redisTemplate.opsForValue().set("user", JSONObject.toJSONString(userEntity));
                return 1;
            }
        }
        return 0;
    }

    @Override
    public User echo(Integer userId) {
        return userDao.echo(userId);
    }
}
